package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.pojo.OrderGoods;
import cc.linker.steplink.crm.merchant.service.NewMallService;
import cc.linker.steplink.crm.merchant.service.ShopOrderService;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.ExternalOrderDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import cc.linker.steplink.crm.merchanth5.service.acs.OauthCheckH5Service;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("shop/order")
public class ShopOrderController {

    @Value("${casclient.clientHost}")
    private String clientHost;
    @Value("${wcpay.smsurl}")
    private String smsurl;
    @Value("${system.scrm.acsScrmWebUrl}")
    private String scrmH5Url;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private NewMallService newMallService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private MallDao mallDao;
    @Autowired
    private MallService mallService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ExternalOrderDao externalOrderDao;

    @Autowired
    private OauthCheckH5Service oauthCheckService;

    @Autowired
    private CommonsService commonsService;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 获取订单列表
     */
    @RequestMapping("/list")
    public Object list(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                       String addressPhone, String orderSn, String realName, String goodsName, String tradeSn,
                       String startTime, String endTime, Integer orderType, Integer status,String mallsName, HttpServletRequest request
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();

        if (!StringUtils.isEmpty(goodsName)) {
            goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            goodsName = goodsName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(realName)) {
            realName = URLDecoder.decode(realName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            realName = realName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(addressPhone)) {
            addressPhone = URLDecoder.decode(addressPhone.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            addressPhone = addressPhone.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            orderSn = URLDecoder.decode(orderSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            orderSn = orderSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(tradeSn)) {
            tradeSn = URLDecoder.decode(tradeSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            tradeSn = tradeSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(mallsName)) {
            mallsName = URLDecoder.decode(mallsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            mallsName = mallsName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("goodsName", goodsName);
        params.put("realName", realName);
        params.put("addressPhone", addressPhone);
        params.put("orderSn", orderSn);
        params.put("tradeSn", tradeSn);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("status", status);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        params.put("mallsName", mallsName);
        Integer payMode = mallService.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        // 大麦
        int type = 1;
        if (!StringUtils.isEmpty(salerId)) {
            //联盟商家
            params.put("salerId", salerId);
            params.put("belongId", salerId);
            type=2;
        }
        params.put("orderType",orderType);
        params.put("type",type);
        String mallsCustomerId = null;
        if(!StringUtils.isEmpty(mallsName) && (orderType!=null && orderType!=3) ){
            mallsCustomerId = shopOrderService.getMallsCustomerIdByMallsName(mallsName);
            if(mallsCustomerId==null){
                mallsCustomerId = "无此供货商！！！";
            }
            params.put("mallsCustomerId",mallsCustomerId);
        }

        if(!StringUtils.isEmpty(mallsName) && (orderType!=null && orderType==3) ){
            mallsCustomerId = shopOrderService.getMerchantCustomerIdByMallsName(mallsName);
            if(mallsCustomerId==null){
                mallsCustomerId = "无此供货商！！！";
            }
            params.put("mallsCustomerId",mallsCustomerId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopOrderService.list(params));
    }

    /**
     * 导出订单列表
     */
    @RequestMapping("/exportList")
    public void exportList(String addressPhone, String orderSn, String realName, String goodsName, String tradeSn,
                           String startTime, String endTime, Integer status, Integer orderType, HttpServletRequest request, String mallsName,
                           HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();

        if (!StringUtils.isEmpty(goodsName)) {
            goodsName = URLDecoder.decode(goodsName, "UTF-8");
        }
        if (!StringUtils.isEmpty(realName)) {
            realName = URLDecoder.decode(realName, "UTF-8");
        }
        if (!StringUtils.isEmpty(mallsName)) {
            mallsName = URLDecoder.decode(mallsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            mallsName = mallsName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("goodsName", goodsName);
        params.put("realName", realName);
        params.put("addressPhone", addressPhone);
        params.put("orderSn", orderSn);
        params.put("tradeSn", tradeSn);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("status", status);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        params.put("mallsName", mallsName);

        Integer payMode = mallService.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        int type = 1;
        if (!StringUtils.isEmpty(salerId)) {
            params.put("salerId", salerId);
            params.put("belongId", salerId);
            type = 2;
        }
        params.put("type",type);
        params.put("orderType",orderType);
        String mallsCustomerId = null;
        if(!StringUtils.isEmpty(mallsName)){
            mallsCustomerId = shopOrderService.getMallsCustomerIdByMallsName(mallsName);
            if(mallsCustomerId==null){
                mallsCustomerId = "无此供货商！！！";
            }
            params.put("mallsCustomerId",mallsCustomerId);
        }
        shopOrderService.exportList(params, response, payMode);
    }

    /**
     * 订单备注
     */
    @RequestMapping("/remark")
    public void remark(@RequestBody Map<String, Object> remark,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<String, Object>();
        if (remark.containsKey("orderId") && remark.containsKey("sellerRemark")) {
            Long orderId = Long.valueOf(remark.get("orderId").toString());
            String sellerRemark = remark.get("sellerRemark").toString();
            String orgId = userinfo.getOrgId();
            params.put("orderId", orderId);
            params.put("sellerRemark", sellerRemark);
            params.put("orgId", orgId);
            Integer payMode = mallService.getPayModeByOrgId(params);
            params.put("payMode", payMode);
            params.put("orderType", remark.get("orderType"));
            int i = shopOrderService.remark(params);
            if (i < 1) {
                throw new GlobalException(new ResponseException(400, "备注失败"));
            }
        } else {
            throw new GlobalException(new ResponseException(400, "缺少参数"));
        }
    }

    /**
     * 发货
     */
    @RequestMapping("/delivery")
    public int delivery(@RequestBody Map<String, Object> record,HttpServletRequest request) throws UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Long expressId = null;
        if (record.get("expressId").toString() != null && !record.get("expressId").toString().equals("")) {
            expressId = Long.valueOf(record.get("expressId").toString());
        }
        String expressName = null;
        if (record.get("expressName").toString() != null && !record.get("expressName").toString().equals("")) {
            expressName = record.get("expressName").toString();
        }
        Long orderId = Long.valueOf(record.get("orderId").toString());
        List goodsIds = (List) record.get("goodsIds");
        String shippingCode = record.get("shippingCode").toString();
        Integer shippingType = Integer.parseInt(record.get("shippingType").toString());

//        JSONArray jsonarr = JSONArray.fromObject(goodsIds);
        List<OrderGoods> orderList = new ArrayList<>();
        if (goodsIds != null && goodsIds.size() > 0) {
//            for (int i = 0; i < jsonarr.size(); i++) {
            for (Object goodsId : goodsIds) {
                Map goodsMap = (Map) goodsId;

                OrderGoods order = new OrderGoods();
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
//                JSONObject job = jsonarr.getJSONObject(i);
                order.setGoodsId(Long.valueOf(goodsMap.get("goodsId").toString()));
                order.setRecId(Long.valueOf(goodsMap.get("recId").toString()));
                if (StringUtils.isEmpty(goodsMap.get("newsku"))) {
                    order.setSkuInfo(null);
                } else {
                    order.setSkuInfo(goodsMap.get("newsku").toString());
                }
                orderList.add(order);
            }
        }
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        params.put("sendType", "delivery");
        params.put("orderType", record.get("orderType"));
        params.put("orgId", orgId);
        params.put("orderId", orderId);
        params.put("expressId", expressId);
        params.put("expressName", expressName);
        params.put("goodsIds", orderList);
        params.put("shippingCode", shippingCode);
        params.put("shippingType", shippingType);
        Integer payMode = mallDao.getPayModeByOrgId(params);
        if (payMode == null) {
            payMode = 1;
        }
        params.put("payMode", payMode);
        //剩余未发货个数
        int count = shopOrderService.delivery(params);
        //获取手机号和公众号名称
        Map<String, Object> msgInfo = shopOrderService.getMsgInfo(params);
        String phone = (String) msgInfo.get("phone");
        String publicName = (String) msgInfo.get("publicName");
        //TODO 发货通知
        //发货通知(模板)
        Integer orderType = record.containsKey("orderType") ? Integer.valueOf(record.get("orderType").toString()) : 1;
        Map orderInfo = shopOrderService.getOrderInfoById(orderId, payMode,orderType);
        dynamicService.recording(request, 13,"对"+orderInfo.get("orderSn")+"的订单进行发货");

        String receiveInfo = orderInfo.get("realName") + " " + orderInfo.get("phone") + " " + orderInfo.get("province") + orderInfo.get("city") + orderInfo.get("area") + orderInfo.get("address");
        Map<String, String> orderParam = new HashMap<>();
        orderParam.put("sendType", "delivery");
        orderParam.put("orgId", orderInfo.get("orgId").toString());
        orderParam.put("orderSn", (String) orderInfo.get("orderSn"));
        String sendTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orderParam.put("sendTime", sendTime);
        orderParam.put("expressCompany", expressName == null ? "不需要物流" : expressName);
        orderParam.put("expressSn", shippingType == 0 ? "不需要物流" : shippingCode);
        orderParam.put("receiveInfo", receiveInfo);

        String h5url = scrmH5Url + "/userCenter.html?goto=orderlist?activeTab=30";
        String h5urlEncode = URLEncoder.encode(h5url, "UTF-8");
        String url = clientHost + "/personal/login?token=" + purchaseProcessDao.getTokenByOrgId(orderInfo.get("orgId").toString()) + "&m=" + h5urlEncode;

        orderParam.put("url", url);
        orderParam.put("openid", purchaseProcessDao.getOpenIdByCustomerId((String) orderInfo.get("customerId")));
        LOGGER.info("setTemplateMessageList---"+ com.alibaba.fastjson.JSON.toJSONString(orderParam));
        purchaseProcessService.setTemplateMessageList(orderParam);

        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", "9001");
        nvps.put("mobilNumber", phone);
        nvps.put("params", "{name=" + publicName + "公众号}");
        nvps.put("token", null);
        String result = smsService.sendMsg(orgId, nvps);

        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            //todo 记录短信发送失败日志
        }
        return count;
    }


    /**
     * 获取配送公司
     */
    @RequestMapping("/getExpress")
    public Object getExpress() {
        return shopOrderService.getExpress();
    }

    /**
     * 获取订单详情
     */
    @RequestMapping("/getOrder")
    public Object getOrder(
            String orderSn,
            HttpServletRequest request
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        if (null == orderSn || orderSn.isEmpty()) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        params.put("orderSn", orderSn);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        if (!StringUtils.isEmpty(salerId)) {
            params.put("belongId", salerId);
        }
        Integer payMode = mallDao.getPayModeByOrgId(params);
        if (payMode == null) {
            payMode = 1;
        }
        params.put("payMode", payMode);
        return shopOrderService.getOrder(params);
    }

    @GetMapping("/getorderexpress")
    public Object getOrderExpress(
            String orderSn ){
        return shopOrderService.getOrderExpress(orderSn);
    }

    /**
     * 关闭订单
     */
    @RequestMapping("/closeOrder")
    public void closeOrder(
            @RequestBody Map<String, Object> record,
            HttpServletRequest request
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<String, Object>();
        if (record.containsKey("orderSn")) {
            params.put("orderSn", record.get("orderSn").toString());
            params.put("orgId", orgId);
            Integer payMode = mallDao.getPayModeByOrgId(params);
            if (payMode == null) {
                payMode = 1;
            }
            params.put("payMode", payMode);
            int i = shopOrderService.closeOrder(params);
            if (i < 1) {
                throw new GlobalException(new ResponseException(400, "关闭订单失败"));
            }
        } else {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
    }



    /**
     * 发货
     */
    @PostMapping("/externalDelivery")
    public void externalDelivery(@RequestBody Map<String, Object> record, HttpServletRequest request) throws UnsupportedEncodingException {
        String token = "";
        if (record.get("token") != null && record.get("token") != "") {
            token = record.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if(!flag){
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }

        String orderSn = null;
        if (record.get("orderSn") != null && !record.get("orderSn").toString().equals("")) {
            orderSn = record.get("orderSn").toString();
        }
        String expressName = null;
        if (record.get("expressName").toString() != null && !record.get("expressName").toString().equals("")) {
            expressName = record.get("expressName").toString();
        }
        Map<String, Object> map = externalOrderDao.getOrder(orderSn);
         Long orderId = null;
        String orgId = "";
         if(map.get("orderId")!=null){
             orderId=  Long.valueOf(map.get("orderId").toString());
         }
        if(map.get("orgId")!=null){
            orgId = map.get("orgId").toString();
        }
        List goodsIds = (List) record.get("goodsIds");
        String shippingCode = record.get("shippingCode").toString();
        Integer shippingType = Integer.parseInt(record.get("shippingType").toString());

        List<OrderGoods> orderList = new ArrayList<>();
        if (goodsIds != null && goodsIds.size() > 0) {
            for (Object goodsId : goodsIds) {
                Map goodsMap = (Map) goodsId;
                OrderGoods order = new OrderGoods();
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                order.setGoodsId(Long.valueOf(goodsMap.get("goodsId").toString()));
                order.setRecId(Long.valueOf(goodsMap.get("recId").toString()));
                orderList.add(order);
            }
        }
        //String orgId = userinfo.getOrgId();

        Map<String, Object> params = new HashMap<>();
        params.put("sendType", "delivery");
        params.put("orgId", orgId);
        params.put("orderId", orderId);
        params.put("expressName", expressName);
        params.put("goodsIds", orderList);
        params.put("shippingCode", shippingCode);
        params.put("shippingType", shippingType);
        params.put("orderType", record.get("orderType"));
        Integer payMode = mallDao.getPayModeByOrgId(params);
        if (payMode == null) {
            payMode = 0;
        }
        params.put("payMode", payMode);
        //剩余未发货个数
        int count = shopOrderService.delivery(params);
        //获取手机号和公众号名称
        Map<String, Object> msgInfo = shopOrderService.getMsgInfo(params);
        String phone = (String) msgInfo.get("phone");
        String publicName = (String) msgInfo.get("publicName");
        //TODO 发货通知
        //发货通知(模板)
        Integer orderType = record.containsKey("orderType") ? Integer.valueOf(record.get("orderType").toString()) : 1;
        Map orderInfo = shopOrderService.getOrderInfoById(orderId, payMode,orderType);
        dynamicService.recording(request, 13,"对"+orderInfo.get("orderSn")+"的订单进行发货");
        String receiveInfo = orderInfo.get("realName") + " " + orderInfo.get("phone") + " " + orderInfo.get("province") + orderInfo.get("city") + orderInfo.get("area") + orderInfo.get("address");
        Map<String, String> orderParam = new HashMap<>();
        orderParam.put("sendType", "delivery");
        orderParam.put("orgId", orderInfo.get("orgId").toString());
        orderParam.put("orderSn", (String) orderInfo.get("orderSn"));
        String sendTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orderParam.put("sendTime", sendTime);
        orderParam.put("expressCompany", expressName == null ? "不需要物流" : expressName);
        orderParam.put("expressSn", shippingType == 0 ? "不需要物流" : shippingCode);
        orderParam.put("receiveInfo", receiveInfo);

        String h5url = scrmH5Url + "/userCenter.html?goto=orderlist?activeTab=30";
        String h5urlEncode = URLEncoder.encode(h5url, "UTF-8");
        String url = clientHost + "/personal/login?token=" + purchaseProcessDao.getTokenByOrgId(orderInfo.get("orgId").toString()) + "&m=" + h5urlEncode;

        orderParam.put("url", url);
        orderParam.put("openid", purchaseProcessDao.getOpenIdByCustomerId((String) orderInfo.get("customerId")));
        purchaseProcessService.setTemplateMessageList(orderParam);

        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", "9001");
        nvps.put("mobilNumber", phone);
        nvps.put("params", "{name=" + publicName + "公众号}");
        nvps.put("token", null);
        String result = smsService.sendMsg(orgId, nvps);

        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            //todo 记录短信发送失败日志
        }
    }


    /**
     * 采购订单列表
     * @param pageIndex
     * @param pageSize
     * @param orderSn
     * @param purchaseSn
     * @param startTime
     * @param endTime
     * @param status
     * @param session
     * @return
     */
    @GetMapping("/mallslist")
    public Object mallsList(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            String orderSn,String purchaseSn, String startTime, String endTime,
            Integer status,HttpServletRequest request
    ) throws UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        if (!StringUtils.isEmpty(salerId)) {
            params.put("salerId", salerId);
        }
        if (!StringUtils.isEmpty(purchaseSn)) {
            purchaseSn = URLDecoder.decode(purchaseSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            purchaseSn = purchaseSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            orderSn = URLDecoder.decode(orderSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            orderSn = orderSn.replaceAll("%", "/%");
        }
        params.put("orgId", orgId);
        params.put("orderSn", orderSn);
        params.put("purchaseSn", purchaseSn);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("status",status);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopOrderService.mallsList(params));
    }

    /**
     * 导出导购订单
     * @param orderSn
     * @param purchaseSn
     * @param startTime
     * @param endTime
     * @param status
     * @param session
     * @param response
     */
    @GetMapping("/exportmallslist")
    public void exportMallsList(
            String orderSn,String purchaseSn, String startTime, String endTime,
            Integer status, HttpServletRequest request,HttpServletResponse response
    ) throws UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        if (!StringUtils.isEmpty(salerId)) {
            params.put("salerId", salerId);
        }
        if (!StringUtils.isEmpty(purchaseSn)) {
            purchaseSn = URLDecoder.decode(purchaseSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            purchaseSn = purchaseSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            orderSn = URLDecoder.decode(orderSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            orderSn = orderSn.replaceAll("%", "/%");
        }
        params.put("orgId", orgId);
        params.put("orderSn", orderSn);
        params.put("purchaseSn", purchaseSn);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("status",status);
        Integer payMode = mallService.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        shopOrderService.exportMallsList(params, response, payMode);
    }

    /**
     * 获取采购订单详情
     * @param purchaseSn
     * @param session
     * @return
     */
    @GetMapping("/getmallsorder")
    public Map<String,Object> getMallsOrder(
            String purchaseSn,
            HttpServletRequest request
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        if (null == purchaseSn || purchaseSn.isEmpty()) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        params.put("purchaseSn", purchaseSn);
        params.put("orgId", orgId);
        Integer payMode = mallDao.getPayModeByOrgId(params);
        if (payMode == null) {
            payMode = 0;
        }
        params.put("payMode", payMode);
        return shopOrderService.getMallsOrder(params);
    }

    @GetMapping("/getrefundinfo")
    public Map<String,Object> getRefundInfo(Integer recId)
    {

        return shopOrderService.getRefundInfo(recId);
    }


    @GetMapping("/againrefund")
    public void againRefund(String protectCode,HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String,Object> params = new HashMap<>();
        String orgId = userinfo.getOrgId();
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        if (!StringUtils.isEmpty(salerId)) {
            params.put("salerId", salerId);
        }
        params.put("orgId", orgId);
        params.put("protectCode",protectCode);
        shopOrderService.againRefund(params);
    }


    /**
     * 获取物流信息
     * @param shippingCode 快递单号
     * @return
     */
    @GetMapping("/getexpressinfo")
    public Map<String,Object> getExpressInfo(String shippingCode,String orderSn){
        Map<String, Object> expressList = commonsService.getExpressList(shippingCode);
        if("0".equals(expressList.get("status"))){
            Map data = (Map)expressList.get("result");
            data.put("infoStatus","0");//物流状态
            return data;
        }else{
            Map<String, Object> mallDetail = mallService.getMallDetail(shippingCode,orderSn);
            Map<String,Object> data = new HashMap<>();
            data.put("infoStatus","1");
            data.put("errorMsg",expressList.get("msg"));
            data.put("mallDetail",mallDetail);
            return data;
        }
    }



    /**
     * 获取亏损订单列表
     */
    @GetMapping("/lossList")
    public Object lossList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                       String addressPhone, String orderSn, String realName, String goodsName, String tradeSn,
                       String startTime, String endTime, Integer orderType,HttpServletRequest request
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();

        if (!StringUtils.isEmpty(goodsName)) {
            goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            goodsName = goodsName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(realName)) {
            realName = URLDecoder.decode(realName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            realName = realName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(addressPhone)) {
            addressPhone = URLDecoder.decode(addressPhone.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            addressPhone = addressPhone.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            orderSn = URLDecoder.decode(orderSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            orderSn = orderSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(tradeSn)) {
            tradeSn = URLDecoder.decode(tradeSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            tradeSn = tradeSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("goodsName", goodsName);
        params.put("realName", realName);
        params.put("addressPhone", addressPhone);
        params.put("orderSn", orderSn);
        params.put("tradeSn", tradeSn);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        Integer payMode = mallService.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        // 大麦
        int type = 1;
        if (!StringUtils.isEmpty(salerId)) {
            //联盟商家
            params.put("salerId", salerId);
            params.put("orgId", salerId);
            params.put("belongId", salerId);
            type=2;
        }
        params.put("orderType",orderType);
        params.put("type",type);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopOrderService.lostList(params));
    }

    /**
     * 导出订单列表
     */
    @RequestMapping("/exportLossList")
    public void exportLossList(String addressPhone, String orderSn, String realName, String goodsName, String tradeSn,
                               String startTime, String endTime, Integer orderType,HttpServletRequest request, HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();

        if (!StringUtils.isEmpty(goodsName)) {
            goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            goodsName = goodsName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(realName)) {
            realName = URLDecoder.decode(realName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            realName = realName.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(addressPhone)) {
            addressPhone = URLDecoder.decode(addressPhone.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            addressPhone = addressPhone.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            orderSn = URLDecoder.decode(orderSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            orderSn = orderSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(tradeSn)) {
            tradeSn = URLDecoder.decode(tradeSn.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            tradeSn = tradeSn.replaceAll("%", "/%");
        }
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("goodsName", goodsName);
        params.put("realName", realName);
        params.put("addressPhone", addressPhone);
        params.put("orderSn", orderSn);
        params.put("tradeSn", tradeSn);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        Integer payMode = mallService.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        String userId = userinfo.getAdminId();
        String salerId = newMallService.getSalerId(userId);
        // 大麦
        int type = 1;
        if (!StringUtils.isEmpty(salerId)) {
            //联盟商家
            params.put("salerId", salerId);
            params.put("orgId", salerId);
            params.put("belongId", salerId);
            type=2;
        }
        params.put("orderType",orderType);
        params.put("type",type);
        shopOrderService.exportLossList(params,response);
    }

}
